﻿using System;
using System.IO;
using Flexible.Interfaces;

namespace Flexible.Framework
{
    class PluginActivator
    {
        readonly Type pluginType;
        bool enabled;
        IPlugin plugin;
        bool isApplication;

        public PluginActivator(Type pluginType)
        {
            this.pluginType = pluginType;
            this.plugin = pluginType.GetConstructor(Type.EmptyTypes).Invoke(new object[0]) as IPlugin;
            this.isApplication = pluginType.GetInterface("Flexible.Interfaces.IApplication") != null;
        }

        public bool Enabled { get { return enabled; } }

        public string PluginId { get { return plugin.Signature.Id; } }

        public IPlugin Plugin { get { return plugin; } }

        public bool IsApplication { get { return isApplication; } }

        internal void Activate(PluginActivateContext context, Stream settingsInput)
        {
            if (!enabled)
            {
                enabled = true;
                plugin.LoadSettings(settingsInput);
                plugin.Enable(context);
            }
        }

        internal void Deactivate(PluginActivateContext context, Stream settingsOutput)
        {
            if (enabled)
            {
                enabled = false;

                plugin.Disable(context);
                plugin.SaveSettings(settingsOutput);
            }
        }
    }
}
